package com.ruoyi.framework.aspectj;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 耗时统计
 */
@Aspect
@Component
public class WebTakeTimeAspect {

    private static final Logger logger = LoggerFactory.getLogger(WebTakeTimeAspect.class);

    //统计请求的处理时间
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    /**
     * 带有@TakeTime注解的方法
     */
    @Pointcut("@annotation(com.ruoyi.common.annotation.WebTakeTime)")
    public void log() {

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());
    }

    @AfterReturning(returning = "responseBody", pointcut = "log()")
    public void doAfterReturning(Object responseBody) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        long takeTimes = System.currentTimeMillis() - startTime.get();
        if (takeTimes > 1000) {
            logger.info("[紧急]请求执行时间：{}毫秒，路径：{}", takeTimes,request.getRequestURI());
        } else if (takeTimes > 500) {
            logger.info("[警告]请求执行时间：{}毫秒，路径：{}", takeTimes,request.getRequestURI());
        } else logger.info("[正常]请求执行时间：{}毫秒，路径：{}", takeTimes,request.getRequestURI());
    }
}
